package com.joe.updemo.utils.manager;

import android.app.Activity;
import android.content.Context;
import android.os.Process;
import com.joe.updemo.utils.PayContext;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lj on 2018/1/18 0018.
 */

public class PageManagement {
    private static final List<Activity> activityList = new ArrayList<>();
    private static Context mContext;

    private PageManagement() {
    }

    public synchronized static PageManagement getInstance() {
        return holder.appUtil;
    }

    public void init(Context context) {
        mContext = context;
    }

    public void pushAC(Activity activity) {
        activityList.add(activity);
    }

    public void removeAC(Activity activity) {
        activityList.remove(activity);
    }

    public void finishAc(Class<?> clazz) {
        if (clazz != null) {
            if (containAc(clazz)) {
                for (Activity ac : activityList) {
                    if (ac.getClass().equals(clazz)) {
                        ac.finish();
                    }
                }
            }
        }
    }

    private boolean containAc(Class<?> clazz) {
        for (Activity activity : activityList) {
            if (activity.getClass().equals(clazz)) {
                return true;
            }
        }
        return false;
    }

    public void finishAllAC() {
        for (Activity activity : activityList) {
            activity.finish();
        }
    }

    public Class getTopAC() {
        return activityList.isEmpty() ? null : activityList.get(activityList.size() - 1).getClass();
    }

    public void exit() {
        getInstance().finishAllAC();
        Process.killProcess(Process.myPid());
        PayContext.isAppFinish = true;
        PayContext.timeRunning = false;
    }

    public Context getContext() {
        return mContext;
    }

    private static class holder {
        private static final PageManagement appUtil = new PageManagement();
    }
}
